package com.future.controller;

import javax.validation.constraints.NotNull;

import com.future.common.annotation.ControllerMapping;
import com.future.common.base.BaseController;
import com.future.common.global.GlobalPara;
import com.future.dao.SysUserDao;
import com.future.dao.TeacherDao;
import com.future.model.SysUser;
import com.future.requestbean.Teacher;
import com.future.requestbean.TeacherUpdate;
import com.future.service.SysUserService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.tx.Tx;

@ControllerMapping("/teacher")
public class TeacherController extends BaseController {
	@Inject
	private TeacherDao teacherDao;
	@Inject
	private SysUserService sysUserService;
	@Inject
	private SysUserDao sysDao;

	public void getTeachers() {
		renderResult("teachers", this.teacherDao.getTeachers());
	}

	@Before(Tx.class)
	public void deleteTeacher(@NotNull(message = "选择要删除的老师") Long teacherid) {
		this.teacherDao.deleteById(teacherid);
		SysUser sysUser = this.sysDao.getSysUserByUserTypeAndUserInfoId(teacherid, GlobalPara.TEACHER_TYPE);
		this.sysDao.deleteById(sysUser.getUserid());
		renderSuccess();
	}

	@Before(Tx.class)
	public void addTeacher() {
		Teacher teacher = getJsonBody(Teacher.class);
		this.sysUserService.checkUserNameExisted(teacher.getLoginUsername());
		com.future.model.Teacher t = beanToModel(teacher, com.future.model.Teacher.class);
		this.teacherDao.save(t);
		Long teacherId = t.getTeacherid();

		String username = teacher.getLoginUsername();
		this.sysUserService.saveUser(username, GlobalPara.TEACHER_TYPE, teacherId);
		renderSuccess();
	}

	@Before(Tx.class)
	public void updateTeacher() {
		// TeacherUpdate teacherUpdate = getJsonBody(TeacherUpdate.class);
		// com.future.model.Teacher t = beanToModel(teacherUpdate,
		// com.future.model.Teacher.class);
		// this.teacherDao.update(t);
		// String loginUsername = teacherUpdate.getLoginUsername();
		// Long teacherId = teacherUpdate.getTeacherid();
		// SysUser sysUser =
		// this.sysDao.getSysUserByUserTypeAndUserInfoId(teacherId,
		// GlobalPara.TEACHER_TYPE);
		// this.sysUserService.checkUserNameExisted(loginUsername,
		// sysUser.getUserid());
		// sysUser.setUsername(loginUsername);
		// sysUser.update();
		com.future.model.Teacher teacher = getJsonBodyToModel(TeacherUpdate.class, com.future.model.Teacher.class);
		this.teacherDao.update(teacher);
		renderSuccess();
	}
}
